package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-resty/resty/v2"
)

func main() {
	r := gin.Default()
	client := resty.New()

	r.GET("/ping", func(c *gin.Context) {
		// Call the /ping endpoint on user-service
		var user map[string]string

		client.R().
			SetResult(&user).
			Get("http://user-service/ping")

		// Call the /ping endpoint on order-service
		var order map[string]string

		client.R().
			SetResult(&order).
			Get("http://order-service/ping")

		c.JSON(http.StatusOK, gin.H{
			"orderMessage": order["message"],
			"userMessage":  user["message"],
		})
	})

	r.GET("/orders", func(c *gin.Context) {
		var order map[string]any

		client.R().
			SetResult(&order).
			Get("http://order-service/orders")

		c.JSON(http.StatusOK, order)
	})

	r.Run(":8080")
}

// package main

// import (
// 	"log"
// 	"net"
// 	"net/http"

// 	"github.com/gin-gonic/gin"
// )

// func main() {
// 	// Bind to a random port
// 	listener, err := net.Listen("tcp", ":0") // :0 means "pick any available port"

// 	if err != nil {
// 		log.Fatalf("Failed to bind: %v", err)
// 	}

// 	defer listener.Close()

// 	log.Printf("Listening on %s", listener.Addr())

// 	r := gin.Default()

// 	r.GET("/ping", func(c *gin.Context) {
// 		c.JSON(http.StatusOK, gin.H{"message": "pong from user-service"})
// 	})

// 	r.GET("/orders", func(c *gin.Context) {
// 		c.JSON(http.StatusOK, gin.H{"orders": []string{"Alice", "Bob"}})
// 	})

// 	// Use listener instead of hardcoded port
// 	if err := http.Serve(listener, r); err != nil {
// 		log.Fatalf("Failed to serve: %v", err)
// 	}
// }
